<template>
  <!-- <a-button type="primary" @click="hideMask">预览</a-button> -->
  <div class="mixed-simulation">
    <!-- 手机顶部 -->

    <div class="mobile-header">
      <div class="time">{{ currentTime }}</div>
      <div class="wife">
        <cu-icon type="icon-xinhao" style="font-size: 12px"></cu-icon>
        <cu-icon
          type="icon-wife"
          style="margin: 0 2px; font-size: 14px"
        ></cu-icon>
        <cu-icon type="icon-electricity-full" style="font-size: 14px"></cu-icon>
      </div>
    </div>
    <!-- 视频预览 -->
    <div class="top-video">
      <!-- 视频 -->
      <video
        id="video"
        :src="videoUrl"
        preload="auto"
        v-show="videoUrl"
        controls
        @pause="isPlaying = true"
        @play="isPlaying = false"
        controlslist="nodownload noplaybackrate "
        disablePictureInPicture
      >
        <source :src="videoUrl" type="video/mp4" />
        <source :src="videoUrl" type="video/quicktime" />
        <source :src="videoUrl" type="video/mpeg" />
        <source :src="videoUrl" type="video/3gpp" />
      </video>
      <!-- 播放按钮 -->
      <div
        class="control-btn"
        @click="playVideo"
        v-if="isPlaying && videoUrl && !spinning && !showMask"
      >
        <play-circle-outlined />
      </div>
    </div>
    <div class="video-mask">
      <div class="tip-click-view" v-if="showMask" @click="hideMask">
        <div style="text-align: center">请点击查看</div>
        <div style="text-align: center">模拟效果</div>
        <div style="color: red; font-size: 13px">预览播放低像素视频</div>
        <div style="color: red; font-size: 13px">正式生成会产出高像素视频</div>
      </div>
      <!-- <div class="tip-click-view" v-else> -->
      <div class="tip-click-view" v-if="spinning">
        <a-spin size="large" :spinning="spinning" tip="视频合成中..."></a-spin>
      </div>
    </div>
    <!-- 底部视频描述 -->
    <div class="bottom-desc">
      <div class="materials_count">
        <p>预估混剪视频总量</p>
        <span
          ><i style="font-style: normal; font-weight: 600">
            {{
              materialsCount > 0 && materialsCount <= 1000
                ? materialsCount
                : !!materialsCount && materialsCount > 1000
                ? 1000
                : "--"
            }}
            <!-- {{ materialsCount }} --> </i
          ><i style="font-style: normal">个</i></span
        >
      </div>
      <div class="materials_time">
        <p>预估混剪单视频时长</p>
        <span
          ><i style="font-style: normal; font-weight: 600">{{
            materialTotalMaxDuration
          }}</i
          ><i style="font-style: normal">秒</i></span
        >
      </div>
    </div>
  </div>
</template>

<script>
import {
  defineComponent,
  reactive,
  toRefs,
  computed,
  ref,
  onUnmounted,
  onMounted,
  watch,
} from "vue";
import {
  PauseOutlined,
  CloseOutlined,
  CaretRightOutlined,
  PlayCircleOutlined,
} from "@ant-design/icons-vue";
import { useRouter } from "vue-router";
import request from "@/common/utils/request";
import { useStore } from "vuex";
import { message } from "ant-design-vue";
import { nanoid } from "nanoid";
import dayjs from "dayjs";
import { getSubmitData } from "../../utools/index.js";

export default defineComponent({
  name: "mixedCutCreat",
  components: {
    PauseOutlined,
    CloseOutlined,
    CaretRightOutlined,
    PlayCircleOutlined,
  },
  props: {
    queryData: {
      type: Object,
    },
  },
  setup(props) {
    const router = useRouter();
    const store = useStore();
    // 仓库中的混剪数据
    const VideoMashup = computed(() => {
      return store.state.shotstack.VideoMashup;
    });
    const state = reactive({
      showVideo: false, //控制视频是否显示
      isPlaying: false, //控制播放控件
      showMask: true, //遮罩层显示隐藏
      videoUrl: "", //视频地址
      spinning: false, //spin加载
    });

    // 判断仓库视频数据没有空值
    const allVideoGroup = computed(() => {
      return store.getters.allVideoGroup;
    });
    // 播放视频
    const playVideo = () => {
      state.isPlaying = false;
      const video = document.getElementById("video");
      video.play();
    };
    // 视频预览
    const hideMask = async () => {
      if (!allVideoGroup.value)
        return message.warning("视频组中的素材不能为空");
      // 判断有没有示例素材
      let isHasExplateUrl = VideoMashup.value.resource_data.some((item) =>
        item.material_list.some(
          (ele) => ele.system_default && ele.system_default == 1
        )
      );
      if (isHasExplateUrl) {
        return message.warning("请替换示例素材");
      }

      if (!VideoMashup.value.name) {
        // VideoMashup.value.name = '新建模板'
        return message.warning("请输入模板名称");
      }

      state.showMask = false;
      state.spinning = true;
      const submitData = getSubmitData();

      let res;
      try {
        if (props.queryData.useType == "use") {
          res = await request.post("/work_ai", `/user/shotstack/clip/preview`, {
            ...submitData,
            id: 0,
            type: 0,
            unique_id: nanoid(),
            preview_type: 1,
          });
          if (res?.code && res.code != 1000) {
            throw new Error("预览失败");
          } else {
            res.result && getPreviewVideo(res.result.id);
          }
        } else {
          res = await request.post("/work_ai", `/user/shotstack/clip/preview`, {
            // ...VideoMashup.value,
            ...submitData,
            preview_type: 1,
          });
          console.log(res, "预览结果");
          if (res?.code && res.code != 1000) {
            throw new Error("预览失败");
          } else {
            res.result && getPreviewVideo(res.result.id);
          }
        }
      } catch (error) {
        timerId.value && clearTimeout(timerId.value);
        state.showMask = true;
        state.spinning = false;
        message.error("视频生成失败!");
      }
    };

    const timerId = ref(null);
    // 获取轮询获取预览的视频
    const getPreviewVideo = async (id) => {
      if (!allVideoGroup.value)
        return message.warning("视频组中的素材不能为空");
      state.spinning = true;
      try {
        let res;
        if (props.queryData.useType == "use") {
          res = await request.get("/work_ai", `/user/shotstack/preview/video`, {
            id,
            type: 0,
          });
        } else {
          res = await request.get("/work_ai", `/user/shotstack/preview/video`, {
            id,
            type: VideoMashup.value.type,
          });
        }

        if (res?.code && res?.code != 1000) {
          throw new Error("预览失败");
        }

        if (!res.result) {
          timerId.value = setTimeout(() => {
            getPreviewVideo(id);
            return;
          }, 5000);
        } else if (res.result !== null) {
          state.spinning = false;

          state.videoUrl = res.result.target_url;
          console.log(state.videoUrl, "视频地址视频地址视频地址");
          state.isPlaying = true;
        }
      } catch (error) {
        timerId.value && clearTimeout(timerId.value);
        state.showMask = true;
        state.spinning = false;
        message.error("视频生成失败!");
      }
    };

    // 侦听变化, 停止请求, 恢复查看预览效果
    watch(
      () => VideoMashup.value,
      (nv, ov) => {
        timerId.value && clearTimeout(timerId.value);
        state.showMask = true;
        state.spinning = false;
        state.videoUrl = "";
      },
      {
        deep: true,
      }
    );
    onUnmounted(() => {
      timerId.value && clearTimeout(timerId.value);
    });
    // 预估视频数量
    const materialsCount = computed(() => {
      let allEmpty = false; // Flag to check if all material_lists are empty
      const count = store.state.shotstack.VideoMashup.resource_data?.reduce(
        (acc, item) => {
          // debugger
          if (item.material_list.length > 0) {
            if (item.time_strategy.type == 0 || item.time_strategy.type == 1) {
              // 视频原始时长或视频自动变速 => 不论是单镜头还是智能混剪 都为此项视频的素材数量
              acc.push(item.material_list.length);
              return acc;
            } else if (item.time_strategy.type == 2) {
              // 随音频截取
              if (item.type == 0) {
                // 单镜头混剪 => 只取视频组的实际视频数量
                acc.push(item.material_list.length);
                return acc;
              } else if (item.type == 2) {
                // 智能混剪 => 用视频的总长度 除以截取的 end_time长度
                let video_num = 0;
                item.material_list.forEach((ele) => {
                  video_num += +(
                    +ele.material_duration / +ele.end_time
                  ).toFixed(0);
                });
                console.log(video_num, "随音频智能截取+智能混剪");
                acc.push(video_num);
                return acc;
              }
            } else if (item.time_strategy.type == 3) {
              // 原始时长
              // 固定时长
              if (item.type == 0) {
                // 单镜头混剪 => 只取视频组的实际视频数量
                acc.push(item.material_list.length);
                return acc;
              } else if (item.type == 2) {
                // 智能混剪 => 用视频的总长度 除以截取的 end_time长度
                let video_num = 0;
                item.material_list.forEach((ele) => {
                  if (ele.scene_type == "image") {
                    video_num += 1;
                  } else {
                    video_num += +(
                      ele.material_duration / ele.end_time
                    ).toFixed(0);
                  }
                });
                acc.push(video_num);
                return acc;
              }
            }
          } else {
            allEmpty = true; // Set the flag to false if any material_list is not empty
            return acc;
          }
        },
        []
      );
      const allCount = count?.reduce(
        (accumulator, currentValue) => accumulator * currentValue,
        1
      );
      return allEmpty ? "--" : allCount;
    });

    const reduceMaterial_list = () => {
      // debugger

      const minAndMax = VideoMashup.value?.resource_data?.reduce(
        (acc, item) => {
          // debugger
          // 每一项的最大和最小值
          let itemMinAndMax = item?.material_list.reduce(
            (itemAcc, ele) => {
              if (item?.time_strategy)
                if (!itemAcc.min || itemAcc.min > ele.end_time) {
                  itemAcc.min = ele.end_time;
                }
              if (!itemAcc.max || itemAcc.max < ele.end_time) {
                itemAcc.max = ele.end_time;
              }
              //   if (!itemAcc.min || itemAcc.min > ele.material_duration) {
              //     itemAcc.min = ele.material_duration;
              //   }
              // if (!itemAcc.max || itemAcc.max < ele.material_duration) {
              //   itemAcc.max = ele.material_duration;
              // }
              return itemAcc;
            },
            { max: null, min: null }
          );
          acc.min += itemMinAndMax.min;
          acc.max += itemMinAndMax.max;
          return acc;
        },
        { max: 0, min: 0 }
      );

      return minAndMax;
    };

    // 处理总时长, 时间大小
    const getTotalDuration = (minAndMax) => {
      if (minAndMax?.max && minAndMax?.min) {
        if (minAndMax.max == minAndMax.min) {
          return +(minAndMax.max / 1000).toFixed(0);
        } else {
          return (
            +(minAndMax.min / 1000).toFixed(0) +
            "-" +
            +(minAndMax.max / 1000).toFixed(0)
          );
        }
      } else {
        return "--";
      }
    };

    // 预估视频时长
    const materialTotalMaxDuration = computed({
      get() {
        const Global_tts = VideoMashup.value.global_tts_config;
        // 使用全局标题的预估时长为
        // 素材的最大和最小时长
        const minAndMax = reduceMaterial_list();
        // debugger
        const isNotEmpty = VideoMashup.value?.resource_data?.every(
          (ele) => ele?.material_list.length
        );
        if (Global_tts?.type == 1) {
          // .some(ele => ele.material_url))
          if (isNotEmpty) {
            // 判断素材时长和文本的时长那个长  用哪个
            // 当前选择的类型(文本 或者 audio)
            const type = Global_tts.configs_type;
            // 判断全局的文本有没有音频数据
            const isVideo = Global_tts.configs.filter((i) => i.tab_id == type);
            if (isVideo.length) {
              if (!!isVideo[0].duration) {
                // 判断总时长 和素材时长那个更大
                const max = Math.max(minAndMax.max, +isVideo[0].duration);
                if (max == minAndMax.max) {
                  return getTotalDuration(minAndMax);
                } else {
                  return Math.ceil(+isVideo[0].duration / 1000);
                }
              } else {
                return getTotalDuration(minAndMax);
              }
            }
          } else {
            return "--";
          }
        } else {
          if (isNotEmpty) {
            return getTotalDuration(minAndMax);
          } else {
            return "--";
          }
        }
      },
    });
    const currentTime = computed(() => {
      return dayjs().format("HH:mm");
    });
    return {
      timerId,
      ...toRefs(state),
      playVideo,
      hideMask,
      getPreviewVideo,
      materialsCount,
      materialTotalMaxDuration,
      currentTime,
    };
  },
});
</script>

<style lang="less" scoped>
video::-webkit-media-controls-fullscreen-button {
  display: none;
}

.mixed-simulation {
  height: 100%;

  overflow-x: hidden;
  overflow-y: auto;
  position: relative;

  .mobile-header {
    height: 30px;
    width: 270px;
    border-top-left-radius: 15px;
    border-top-right-radius: 15px;
    border-bottom: 1px solid rgba(255, 255, 255, 0.2);
    background: black;
    display: flex;
    align-items: center;
    justify-content: space-between;
    color: #fff;
    padding: 10px 10px;
  }

  .video-mask {
    position: absolute;
    top: 0;
    left: 0;

    .tip-click-view,
    .tip-click-add {
      height: 583px;
      border-radius: 15px;
      width: 270px;
      color: #fff;
      display: flex;
      flex-direction: column;
      justify-content: center;
      align-items: center;
      font-size: 24px;
      cursor: pointer;
    }

    .tip-click-add {
      background: black;
    }

    .tip-click-view {
      background: rgba(0, 0, 0, 0.5);
    }
  }

  .top-video {
    cursor: pointer;
    height: 553px;
    width: 270px;
    //     width: 360px;
    // height: 640px;
    position: relative;
    overflow: hidden;
    border-bottom-left-radius: 15px;
    border-bottom-right-radius: 15px;

    video {
      width: 100%;
      height: 553px;
    }

    // 视频暂停播放控制按钮
    .control-btn {
      position: absolute;
      top: 50%;
      left: 50%;
      transform: translate(-50%, -50%);
      color: #fff;
      font-size: 50px;
    }

    .loading {
      position: absolute;
      top: 50%;
      left: 50%;
      transform: translate(-50%, -50%);
    }
  }

  .top-video {
    background: black;
  }

  // 底部视频描述
  .bottom-desc {
    height: 80px;
    width: 270px;
    display: flex;
    margin-top: 10px;
    background: #fff;
    align-items: flex-start;
    background: linear-gradient(133deg, #f6f8fa, rgba(246, 248, 250, 0.3)), #fff;
    border: 1px solid #eaedf1;
    border-radius: 4px;
    box-sizing: border-box;
    display: flex;
    margin-top: 24px;
    padding: 12px 0;
    width: 268px;
    font-family: PingFang SC;
    font-style: normal;

    .materials_count {
      width: 50%;
      font-size: 14px;
      display: flex;
      padding-left: 5px;
      flex-direction: column;
    }

    .materials_time {
      width: 50%;
      padding-right: 5px;
      font-size: 14px;
      display: flex;
      flex-direction: column;
    }

    span {
      font-weight: 700;
      font-size: 14px;

      i {
        font-weight: 400;
        margin-left: 2px;
      }
    }
  }
}
</style>
